import { useRef, useState } from 'react';
import {
  PlusOutlined,
  ManOutlined,
  WomanOutlined,
  CloseSquareOutlined,
  EditOutlined,
} from '@ant-design/icons';
import { Access } from 'umi'
import usePermission from '@/hooks/usePermission';
import { Button, Tag, Space, Switch, message, Tooltip } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import request from 'umi-request';
import { updateAdminUserState } from '@/services/admin-user';
import AdminUserItem from './components/item';

export default () => {
  const actionRef = useRef<ActionType>();
  const [showItem, setShowItem] = useState<boolean>(false);
  const [user, setUser] = useState<ADMIN_USER_API.AdminUser | undefined>(undefined);

  const changeState = async (record: ADMIN_USER_API.AdminUser) => {
    if (record.id === 1) {
      message.warning('【超级管理员】不能被停用');
      return;
    }
    const rsp = await updateAdminUserState({ id: record.id, state: record.state === 0 ? 1 : 0 });
    if (rsp.code === 0) {
      message.success(`${record.state === 0 ? '启用成功' : '禁用成功'}`);
      actionRef?.current?.reload();
    }
  };

  const onClose = () => {
    setUser(undefined);
    setShowItem(false);
  };

  const toAdd = () => {
    setShowItem(true);
  };

  const toEdit = (record: ADMIN_USER_API.AdminUser) => {
    setUser(record);
    setShowItem(true);
  };

  const toFetchList = () => {
    actionRef?.current?.reload();
  };

  const columns: ProColumns<ADMIN_USER_API.AdminUser>[] = [
    {
      title: '账号',
      dataIndex: 'user_no',
      fieldProps: { placeholder: '请输入账号' },
      copyable: true,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '用户名',
      dataIndex: 'username',
      fieldProps: { placeholder: '请输入用户名' },
      align: 'center',
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      fieldProps: { placeholder: '请输入手机号' },
      ellipsis: true,
      align: 'center',
    },
    {
      title: '性别',
      dataIndex: 'gender',
      fieldProps: { placeholder: '请选择性别' },
      hideInTable: true,
      valueEnum: {
        1: { text: '男' },
        2: { text: '女' },
        3: { text: '保密' },
      },
    },
    {
      title: '性别',
      align: 'center',
      dataIndex: 'gender',
      hideInSearch: true,
      width: 80,
      valueEnum: {
        1: { text: <ManOutlined title="男" style={{ color: '#52c41a', fontSize: 18 }} /> },
        2: { text: <WomanOutlined title="女" style={{ color: '#eb2f96', fontSize: 18 }} /> },
        3: {
          text: <CloseSquareOutlined title="保密" style={{ color: '#1890FF', fontSize: 18 }} />,
        },
      },
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      fieldProps: { placeholder: '请输入邮箱' },
      align: 'center',
      ellipsis: true,
    },
    {
      title: '角色',
      align: 'center',
      dataIndex: 't_roles',
      width: 180,
      search: false,
      renderFormItem: (_, { defaultRender }) => {
        return defaultRender(_);
      },
      render: (_, record) => (
        <Space>
          {record.t_roles.map(({ role_name, is_default, id }) => (
            <Tag color={id === 1 ? 'magenta' : is_default === 0 ? 'blue' : ''} key={id}>
              {is_default === 0 ? role_name : `${role_name}(默认)`}
            </Tag>
          ))}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'state',
      hideInTable: true,
      fieldProps: { placeholder: '请选择状态' },
      valueEnum: {
        1: { text: '启用' },
        0: { text: '停用' },
      },
    },
    {
      title: '状态',
      align: 'center',
      dataIndex: 'state',
      hideInSearch: true,
      width: 120,
      render: (text, record) => [
        <Switch
          checkedChildren="启用"
          unCheckedChildren="停用"
          checked={record.state === 1}
          onChange={() => changeState(record)}
        />,
      ],
    },
    {
      title: '创建时间',
      align: 'center',
      dataIndex: 'created_at',
      valueType: 'dateTime',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      fieldProps: { placeholder: ['创建开始时间', '创建结束时间'] },
      valueType: 'dateRange',
      hideInTable: true,
      colSize: 2,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      render: (text, record, _, action) => [
        <Access accessible={usePermission('system:user:update')} fallback={null}>
        <Tooltip title="修改">
          <Button
            type="primary"
            shape="circle"
            icon={<EditOutlined />}
            onClick={() => toEdit(record)}
          />
        </Tooltip>
      </Access>
      ],
    },
  ];

  const fetchList = async (
    params: ADMIN_USER_API.AdminUser & { orderColumn?: string; orderType?: string },
    sort = {},
  ) => {
    const query = { ...params };
    if (JSON.stringify(sort) !== '{}') {
      query.orderColumn = Object.keys(sort)[0];
      query.orderType =
        Object.values(sort)[0] === 'descend'
          ? 'desc'
          : Object.values(sort)[0] === 'ascend'
          ? 'asc'
          : '';
    }
    const rsp = await request<{
      data: { list: ADMIN_USER_API.AdminUser[]; total: number };
      code: number;
    }>('/api/v1/admin_users', {
      params: query,
    });
    if (rsp.code === 0) {
      return {
        data: rsp.data.list,
        total: rsp.data.total,
        success: true,
      };
    }
  };

  return (
    <>
      <ProTable<ADMIN_USER_API.AdminUser>
        columns={columns}
        actionRef={actionRef}
        request={fetchList}
        search={{
          span: 6,
        }}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
        }}
        form={{}}
        dateFormatter="string"
        headerTitle="系统用户"
        toolBarRender={() => [
          <Access accessible={usePermission('system:user:add')} fallback={null}>
           <Button key="button" icon={<PlusOutlined />} type="primary" onClick={toAdd}>
            新增
          </Button>
        </Access>,
        ]}
      />

      {showItem && <AdminUserItem userInfo={user} toFetchList={toFetchList} onClose={onClose} />}
    </>
  );
};
